import cv2
import numpy as np
import io
import time
from PIL import Image, ImageDraw, ImageFont
from .qiniuMain import QiNiuService

qiniuObj = QiNiuService('img')


def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if isinstance(img, np.ndarray):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "lib/qiniucloud/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


def genCert(studentid, nickname, mobile, start_year, start_month, start_day, end_year, end_month, end_day):
    image = cv2.imread("lib/qiniucloud/sq1.jpeg")
    import datetime
    y = datetime.datetime.now().year
    difference = int(y-start_year)
    if difference == 0:
        difference = 1
    else:
        difference += 1
    # cv2.putText(image, u"张某某", (270, 450), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
    image = cv2ImgAddText(image, nickname, 260, 420, (0, 0, 0), 30)
    # image = cv2ImgAddText(image, "代言人", 530, 470, (0, 0, 0), 30)
    # image = cv2ImgAddText(image, "18652701182", 110, 475, (0, 0, 0), 25)
    cv2.putText(image, "%08d" % studentid, (340, 335), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, mobile, (95, 500), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_year), (216, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_month), (312, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_day), (370, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_year+difference), (455, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_month), (550, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)
    cv2.putText(image, str(start_day), (610, 969), cv2.FONT_ITALIC, 0.8, (31, 59, 62), 2)

    # image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
    # cv2.imshow("tmp", image)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    output = io.BytesIO()
    Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), mode='RGB').save(output, format="JPEG")
    data = output.getvalue()
    fileKey, fileUrl = qiniuObj.upload_file_by_steam(data, 'cert_%s_%s.jpg' % (studentid, int(time.time() * 1000000)))
    return fileUrl
